from flask import Flask, Response
from flask_restful import Api
from flask_apispec import FlaskApiSpec
from apispec import APISpec
# from flask_restful_swagger import swagger
from apispec.ext.marshmallow import MarshmallowPlugin
from loguru import logger
from flask_sqlalchemy import SQLAlchemy
from common.logger_tool import InterceptHandler

app = Flask(__name__)
# api = swagger.docs(Api(app, prefix="/api/v1"))
api = Api(app, prefix="/api/v1")
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:root@127.0.0.1:3306/test'
app.config['JSON_AS_ASCII'] = False
app.config.update({
    "APISPEC_SPEC":APISpec(
        title="flask restful api",
        version="v1",
        plugins=[MarshmallowPlugin()],
        openapi_version="2.0"
    ),
    "APISPEC_SWAGGER_URL":"/swagger/",
    "APISPEC_SWAGGER_UI_URL":"/swagger-ui/"
})

logger.add("logs/log.log", level= "DEBUG", rotation='100 MB', compression='zip', 
                           retention="72h", backtrace=True, encoding="utf-8")

# logger.add("logs/log.log", level='DEBUG', rotation="100MB", retention="5 days",  encoding="utf-8")

app.logger.addHandler(InterceptHandler())
db = SQLAlchemy(app)
docs = FlaskApiSpec(app=app)

from resources.demo import Demo
from resources.attachment_resource import AttachmentListResource


# yaml 接口文档显示
import yaml
@app.route("/swagger.yaml")
def generator_swagger_yaml():
    yaml_doc = yaml.safe_dump(yaml.safe_load(docs.spec.to_yaml()), allow_unicode=True)
    return Response(yaml_doc, mimetype="text/yaml")

# 自定义处理参数验证
@app.errorhandler(422)
def handle_validation_error(error):
    logger.info(error.data.get("messages"))
    err_data = {
        "status_code":400,
        "message":  error.data.get("messages")
    }
    return jsonify(err_data), 400